<?

class BasicAuth{
	private $message = "Enter Password";
	private $users = array(
        /*
        'username1' => 'pass1',
		'username2' => 'pass2',
        */
	);

	public function isAuthorized(){
		if(empty($_SERVER['PHP_AUTH_USER'])) return false;
		if(empty($_SERVER['PHP_AUTH_PW'])) return false;
		
		if(!array_key_exists ($_SERVER['PHP_AUTH_USER'], $this->users)) return false;
		if($this->users[$_SERVER['PHP_AUTH_USER']] !== $_SERVER['PHP_AUTH_PW']) return false;
		return true;
	}
	
	public function addUser($name, $pass){
		$this->users[$name] = $pass;
	}
    
    public function getUser(){
        if(empty($_SERVER['PHP_AUTH_USER'])) return false;
        return $_SERVER['PHP_AUTH_USER'];
    }

    public function getPass(){
        if(empty($_SERVER['PHP_AUTH_PW'])) return false;
        return $_SERVER['PHP_AUTH_PW'];
    }
    
    public function setMessage($text){
        $this->message = $text;
    }

	public function authorize(){
		if(!$this->isAuthorized()){
			sleep(2);
			header('WWW-Authenticate: Basic realm="'.$this->message.'"');
			header('HTTP/1.0 401 Unauthorized');
			echo '<h1 style="color:red">Access denied!</h1>';
			exit;
		}
	}

	public function https(){
		if(strpos($_SERVER["HTTP_HOST"], ".ru") === false) return;
		if($_SERVER["HTTPS"] != 'on' && $_SERVER["HTTP_SSL"] != 'on'){
			$link = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			header("Location: $link");
			die("<a href='$link'>$link</a>");
		}
	}
}
?>